'use strict';
let mongoose = require('mongoose');
let autoNumber = mongoose.models['AutoNumber'];

let schema=new mongoose.Schema({
    openid: {
        type: String,
        required: true,
        index: {
            unique: true
        }
    },
    token: String,
    nickname:String,
    sex:Number,
    headimgurl:String,
    id: {
        type: Number,
        required: true,
        index: {
            unique: true
        }
    },
    address: String,
    loginTimes : {
        type: Number,
        "default": 0
    },
    latitude:String,
    longitude:String,
    status:{
        type: Number,
        "default": 0
    }
});
schema.index( {id : 1} , { unique : true });
schema.index( {openid : 1,token:1} , { unique : true });

schema.statics={
    //小程序用户的注册流程
    getRandomId:async function(){
        let id=Math.floor(Math.random()*900000)+100000;
        let user=await this.findOne({id:id});
        if(!!user){
            return await this.getRandomId();
        }else{
            return id;
        }
    },
    xiaoChengXuLogin:async function (userData) {
        let user=await this.findOne({openid:userData.openid});
        if(!user){
            let n=await autoNumber.getNewNumber(modelName);////await this.getRandomId();//
            await this.create(Object.assign(userData,{id:n}));
        }else{
            await this.update({_id:user._id},{$set : userData}, {upsert : true}).exec();
        }
        user=await this.findOne({openid:userData.openid});
        return user;
    }
};

module.exports= schema